<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="关键词"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>

    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" align="center">
        <template slot-scope="{row}">
          <span>{{ row.sale_id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="账号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.real_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="管理城市" align="center">
        <template slot-scope="{row}">
          <span v-for="i in row.managercitys">{{ i.city_name }};</span>
        </template>
      </el-table-column>
      <el-table-column label="身份证号码" align="center">
        <template slot-scope="{row}">
          <span>{{ row.idcard }}</span>
        </template>
      </el-table-column>
      <el-table-column label="手机号码" align="center">
        <template slot-scope="{row}">
          <span>{{ row.mobile }}</span>
        </template>
      </el-table-column>
      <el-table-column label="邀请码" align="center">
        <template slot-scope="{row}">
          <span>{{ row.invite_code }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="状态" class-name="status-col">
        <template slot-scope="{row}">
          <el-tag :type="row.status | statusFilter">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button v-if="row.status=='1'" size="mini" type="warning" @click="handleModifyStatus(row,0)">
            禁用
          </el-button>
          <el-button v-if="row.status=='0'" size="mini" type="success" @click="handleModifyStatus(row,1)">
            启用
          </el-button>
          <el-button type="danger" size="mini" @click="resetPwd(row)">
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="账户名" prop="username">
          <el-input v-model="temp.username" type="text" placeholder="请输入账户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="real_name">
          <el-input v-model="temp.real_name" type="text" placeholder="请输入销售人员姓名" />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="temp.mobile" type="text" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="身份证" prop="idcard">
          <el-input v-model="temp.idcard" type="text" placeholder="请输入身份证号码" />
        </el-form-item>
        <el-form-item label="邀请码" prop="invite_code">
          <el-input v-model="temp.invite_code" type="text" placeholder="请输入邀请码" />
        </el-form-item>
        <el-form-item label="选择上级" prop="parent_id">
          <el-select v-model="temp.parent_id" filterable placeholder="请选择">
            <el-option v-for="(item,index) in this.sale_list" :key="item.sale_id" :label="item.real_name" :value="item.sale_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="管理城市" prop="managercity">
          <el-select v-model="temp.managercity" placeholder="请选择市" filterable multiple="">
            <el-option v-for="(city,index) in this.merchant_city" :key="index" :label="city.name" :value="city.region_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在省份" prop="province">
          <el-select v-model="temp.province" placeholder="请选择省份" filterable @change="getRegionList(temp.province)">
            <el-option
              v-for="(province,index) in this.province_list"
              :key="index"
              :label="province.name"
              :value="province.region_id"
            />

          </el-select>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-select v-model="temp.city" placeholder="请选择市" filterable>
            <el-option v-for="(city,index) in this.city_list" :key="index" :label="city.name" :value="city.region_id" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="createData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
      <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
        <el-table-column prop="key" label="Channel" />
        <el-table-column prop="pv" label="Pv" />
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchList,
  createSale,
  updateSaleStatus,
  resetPwd
} from '@/api/sale'
import {
  backendgetmerchantregion
} from '@/api/finance'
import {
  getRegionList
} from '@/api/system'
import waves from '@/directive/waves' // waves directive
import {
  parseTime
} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'ComplexTable',
  components: {
    Pagination
  },
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    typeFilter(type) {
      return calendarTypeKeyValue[type]
    }
  },
  data() {
    return {
      merchant_city: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        keyword: undefined

      },
      saleListQuery:{
        page: 1,
        limit: 1000,
      },
      province_list: [],
      city_list: [],
      sortOptions: [{
        label: 'ID Ascending',
        key: 'sale_id asc'
      }, {
        label: 'ID Descending',
        key: 'sale_id desc'
      }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {
        username: '',
        real_name: '',
        idcard: '',
        mobile: '',
        status: '1',
        managercity: [8725, 7133]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      dialogPvVisible: false,
      pvData: [],
      sale_list:[],
      rules: {
        username: [{
          required: true,
          message: '账户必须填写',
          trigger: 'change'
        }],
        password: [{
          required: true,
          message: '密码必须输入',
          trigger: 'change'
        }],
        real_name: [{
          required: true,
          message: '销售人员姓名必须输入',
          trigger: 'change'
        }],
        mobile: [{
          required: true,
          message: '手机号码必须输入',
          trigger: 'change'
        }],
        idcard: [{
          required: true,
          message: '身份证号码必须输入',
          trigger: 'blur'
        }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList();
    this.getSaleList();
    this.getRegionList(0)
    this.getMerchantRegionList()
  },
  methods: {
    getMerchantRegionList() {
      backendgetmerchantregion(this.listQuery).then(response => {
        this.merchant_city = response.data
      })
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.0 * 1000)
      })
    },
    getSaleList() {
      this.listLoading = true
      fetchList(this.saleListQuery).then(response => {
        this.sale_list = response.data.data
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.0 * 1000)
      })
    },
    getRegionList(parent_id) {
      const param = { parent_id: parent_id }
      getRegionList(param).then(response => {
        if (parent_id == 0) {
          this.province_list = response.data
        } else {
          this.city_list = response.data
        }
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      const tempData = { sale_id: row.sale_id }
      tempData.status = status
      updateSaleStatus(tempData).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
      row.status = status
    },
    resetPwd(row, status) {
      const tempData = { sale_id: row.sale_id }
      resetPwd(tempData).then(() => {
        this.dialogFormVisible = false
        this.$notify({
          title: 'Success',
          message: 'Update Successfully',
          type: 'success',
          duration: 2000
        })
      })
      this.getList()
    },
    sortChange(data) {
      const {
        prop,
        order
      } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        username: '',
        real_name: '',
        idcard: '',
        mobile: '',
        sale_id: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createSale(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.getList()
            // this.$refs['dataForm'].resetFields();
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.temp.password = ''
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(row, index) {
      console.log(row.sale_id)
      deleteSale(row.sale_id).then(response => {
        this.$notify({
          title: 'Success',
          message: 'Delete Successfully',
          type: 'success',
          duration: 2000
        })
        this.list.splice(index, 1)
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
